import Vue from 'vue'
import Vuex from 'vuex'
import { login, logout, getUserinfo, memberDtl, tenantInfo } from '@/api/user'
import {getSystemConfigDetail} from '@/api/sysConfig'
import { setToken, getToken, clearAll } from '@/utils/auth';
import auth from '@/plugins/auth'
import { routes } from '@/router'
import { dynamicRoutes } from '@/router/routes';
import { setUserInfo, getUserInfo, getTenantInfo, clearAllLocal, getSystemInfo, setSystemInfo } from '@/utils/localStorageUtils'
import md5 from 'blueimp-md5'
import GPS from "@/utils/gps";

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    currentRoute: 'indexLayout',
    childRoute: '',  // 子列表当前路由
    siderBarList: [],
    userInfo: getUserInfo(),
    memberInfo: {},
    roles: [],
    leftBarList: [],     // 左侧导航
    tenantInfo: getTenantInfo(),
    systemInfo: getSystemInfo(),
    locationCenter: [120.74667948763846, 30.76447109698219], // 存储02高德坐标
  },
  getters: {
    roles: state => state.roles,
    tenantInfo: state => state.tenantInfo
  },
  mutations: {
    SET_USER_INFO(state, data){
      state.userInfo = data
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles || []
    },
    SET_SIDERBAR_LIST(state, data) {
      state.siderBarList = data
    },
    SET_MEMBER_INFO(state, data) {
      state.memberInfo = data
    },
    SET_CURRENT_ROUTE_CODE(state, data) {
      state.currentRoute = data.code;
      state.leftBarList = data.children && data.children.length > 1 ? data.children : [];
    },
    SET_CHILD_ROUTE(state, data) {
      state.childRoute = data
    },
    SET_TENANT_INFO: (state, tenantInfo) => {
      state.tenantInfo = tenantInfo
    },
    SET_SYSTEM_INFO(state, data) {
        if(data.locationCenter) {
           const _location = JSON.parse(data.locationCenter);
           state.locationCenter =  GPS.WGS84toGCJ02(..._location);
        }
        state.systemInfo = data;
    }
  },
  actions: {
    login(store, info) {
      return new Promise((resolve, reject) => {
        const loginForm = {
          key: info.key,
          account: info.account,
          verifyCode: info.verifyCode,
          password: md5(`${info.password}:${info.key}`)
        }
        login(loginForm).then((res) => {
          setToken(res.data.token)
          // 登录后获取用户信息存储
          return store.dispatch('getUserInfo')
        }).then(res => {
          resolve(res)
        }).catch((error) => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    getUserInfo(store) {
      return new Promise((resolve, reject) => {
        getUserinfo().then(res => {
            store.dispatch('getSystemConfig')
          return memberDtl({
            id: res.data.id
          })
        }).then(res => {
          store.commit('SET_USER_INFO', res.data);
          setUserInfo(res.data)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    getSystemConfig(store){
        getSystemConfigDetail({type: 2}).then(result => {
            store.commit('SET_SYSTEM_INFO', result.data||{});
            setSystemInfo(result.data||{})
        })
    },
    generateRoutes(store) {
      return new Promise((resolve, reject) => {
        getUserinfo().then(res => {
            getSystemConfigDetail({type: 2}).then(result => {
                store.commit('SET_SYSTEM_INFO', result.data);
                setSystemInfo(result.data)
            })
          if(res.code == 1) {
            store.commit('SET_MEMBER_INFO', res.data)
            store.commit('SET_ROLES', res.data.role ? res.data.role.split(',') : ['ADMIN'])
            const sidebarRouters = filterRouter(dynamicRoutes)
            store.commit('SET_SIDERBAR_LIST', routes.concat(sidebarRouters))
            resolve(sidebarRouters)
          }else{
            reject(res)
          }
        }).catch(error => {
          console.log("error:generateRoutes", error)
          reject(error)
        })
      })
    },
        // 获取租户信息（获取租户profile字段设置用户ext）
    getTenantInfo(store) {
      return new Promise((resolve, reject) => {
        tenantInfo().then(res => {
          store.commit('SET_TENANT_INFO', res.data)
          resolve(res.data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    fedLogOut(store) {
      return new Promise((resolve, reject) => {
        store.commit('SET_ROLES', [])
        store.commit('SET_SIDERBAR_LIST', [])
        store.commit('SET_MEMBER_INFO', [])
        store.commit('SET_USER_INFO', {})
        clearAll()
        clearAllLocal()
        resolve()
      })
    },
        // 退出系统
    logout(store) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
            store.commit('SET_CURRENT_ROUTE_CODE', {code: 'indexLayout', children: []})
          store.commit('SET_USER_INFO', {})
          store.commit('SET_ROLES', [])
          store.commit('SET_SIDERBAR_LIST', [])
          clearAll()
          clearAllLocal()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    setCurrentRoute({commit}, data) {
      commit('SET_CURRENT_ROUTE_CODE', data)
    }
  },
  modules: {
  }
})


// 递归判断动态路由（根据角色加载）
function filterRouter(tree) {
  return tree.filter(route => {

    if (route.children != null && route.children && route.children.length) {
      route.children = filterRouter(route.children)
    }

    if (auth.hasRoleOr(route.meta.roles)) {
      return true
    } else {
      return false
    }
  })
}
